﻿using clf.weighing.entity;
using HandyControl.Tools;
using MyHelper;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Threading;

namespace weighing
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : System.Windows.Application
    {
        [SuppressMessage("ReSharper", "NotAccessedField.Local")]
        private static Mutex AppMutex;

        #region statisc variables
        /// <summary>
        /// 应用程序的名称
        /// </summary>
        private static readonly string AppName = "local_weighing";
        public static User? CurrentUser;
        public static CompanyVo? CurrentCompanyVo;
        public static ScaleHouseVo? CurrentScaleHouseVo;
        /// <summary>
        ///  系统启动时就会赋值
        /// </summary>
        public static InitConfig? initConfig;

        public static InitConfig InitConfig
        {
            get
            {
                initConfig ??= InitializeHelper.InitClientIdAndNumber();
                return initConfig;
            }
            set { initConfig = value; }
        }
        public static String UnitText
        {
            get
            {
                return App.Config.WeighingConfig.Unit == Unit.KG ? "千克" : "吨";
            }
        }
        /// <summary>
        /// 加载完成登录界面时加载
        /// </summary>
        public static LocalConfig Config;
        /// <summary>
        /// 明华读写器设备唯一识别号
        /// </summary>
        public static int MhIcDeviceID;
        /// <summary>
        /// 是不是退出当前账户
        /// </summary>
        public static bool IsLogOut = false;
        /// <summary>
        /// 当前系统 的磅称UI项
        /// </summary>
        public static List<ScaleItem>? scaleItems;
        /// <summary>
        /// 未激活时的限止次数
        /// </summary>
        public static int NoActiveLimits = 0;


        #region 本机使用的临时基础数据      
        //public static List<String> decuationDesList = new() { };
        //public static List<String> RemarkList = new() { }; 
        #endregion

        #endregion


        protected override void OnStartup(StartupEventArgs e)
        {

            string name = App.AppName;
          
            AppMutex = new Mutex(true, name, out var createdNew);

            if (!createdNew)
            {
                var current = Process.GetCurrentProcess();
                foreach (var process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        Win32Helper.SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
                Shutdown();
            }
            else
            {
                //new SplashScreen("themes/img/bcover.jpg").Show(true);
                base.OnStartup(e);

                GlobalData.Init();
                try
                {
                    ConfigHelper.Instance.SetLang(GlobalData.Config.LangName);
                }
                catch (Exception)
                {
                }

                SkinHelper.Init();
                LangHelper.Init();
            }
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Test();

            //UI线程未捕获异常处理事件（UI主线程）
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            CommonFunction.CreateShortcat();

            //CommonFunction.SetAutoStart();

            try
            {
                //0 初始化客户端的ID 或者 编号
            
                //1 .数据库连接已经正常连接 
               
                //2 .设置当前的公司
                InitializeHelper.SetCurrentCompany();

                //3 .设置当前磅房
                InitializeHelper.SetCurrentScaleHouse();

                //4 .是否已经有一个开发的用户,没有添加
                InitializeHelper.InitSysUser();

                new LoginWindow().Show();

                Log.Info(LangHelper.Get(LangKeyNames.RunSuccessed));
            }
            catch (Exception ex)
            {
                var m = LangHelper.Get(LangKeyNames.RunFailured);
                Log.Error(m + "：" + ex.Message + " \r\n" + ex.StackTrace);
                HandyControl.Controls.MessageBox.Show(m + "：" + ex.Message);
                this.Shutdown();
            }

        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {           
            if (App.Current.MainWindow is MainWindow mw)
            {
                mw.mainNotifyIcon.Visibility = Visibility.Collapsed;
                mw.mainNotifyIcon?.Dispose();
            }
        }

        #region 全局异常处理
        //发布时不弹窗  Task线程内未捕获异常处理事件 
        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            //try
            //{
            Exception ex = e.Exception;
#if DEBUG
            string msg = String.Format("{0}\n\n{1}", ex.Message, ex.StackTrace);
            HandyControl.Controls.MessageBox.Show(msg, LangHelper.Get(LangKeyNames.TaskException));
#else
                string innetStackTrace="";
                var msg = LangHelper.Get(LangKeyNames.TaskException) + ": " + ex.Message;
                if (ex.InnerException != null)
                {
                    msg += ";" + ex.InnerException.Message;
                    innetStackTrace = ex.InnerException.StackTrace;
                }
                Log.Error("Task Exception" + msg+" Line:"+CommonFunction.GetExceptionCodeLine(ex), ex.StackTrace+"\r\n"+innetStackTrace, true);
#endif
            //}
            //catch (Exception ex)
            //{
            //    Log.Error("Task Exception" + ex.Message + " Line:" + CommonFunction.GetExceptionCodeLine(ex), ex.StackTrace, true);
            //}

        }

        //UI线程未捕获异常处理事件（UI主线程）
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Exception? ex = e.Exception;
            string msg;
#if DEBUG
            //异常信息 和 调用堆栈信息
            msg = String.Format("{0}\r\n{1}", ex?.Message, ex?.StackTrace);
            HandyControl.Controls.MessageBox.Show(msg, LangHelper.Get(LangKeyNames.UiException));
#else

            msg = LangHelper.Get(LangKeyNames.UiException) + ":" + ex.Message;
            if (ex.InnerException != null)
            {
                msg += ex.InnerException.Message;
            }
            Log.Error(msg, ex.StackTrace, true);
#endif
            e.Handled = true;//表示异常已处理，可以继续运行
        }

        //非UI线程未捕获异常处理事件
        //如果UI线程异常DispatcherUnhandledException未注册，则如果发生了UI线程未处理异常也会触发此异常事件
        //此机制的异常捕获后应用程序会直接终止。没有像DispatcherUnhandledException事件中的Handler=true的处理方式，
        //可以通过比如Dispatcher.Invoke将子线程异常丢在UI主线程异常处理机制中处理
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is Exception ex)
            {
                string msg;
#if DEBUG
                //异常信息 和 调用堆栈信息
                msg = String.Format("{0}\r\n{1}", ex.Message + " " + ex.InnerException?.Message, ex.StackTrace);
                HandyControl.Controls.MessageBox.Show(msg, LangHelper.Get(LangKeyNames.NotUiException));
#else

                msg = LangHelper.Get(LangKeyNames.NotUiException) + " " + ex.Message + " " + ex.InnerException?.Message;
                if (ex.InnerException != null)
                {
                    msg += ex.InnerException.Message;
                }
                Log.Error(msg, ex.StackTrace, true);
#endif

            }
        }

        #endregion

        #region static method




        #endregion


        #region Test

        internal void Test()
        {
            //new TempTest().TestJson();
        }

        #endregion
    }
}
